/*
 * @Description: 相机漫游模式
 */
class ViewController {
  constructor(viewer) {
    this.viewer = viewer;
    this.listener = null;
  }

  /**
   * 第一人称视角-相机视角
   * @param {
   *   position: SampledPositionProperty, //动态位置属性
   *   heading: SimpleProperty, //动态偏航角属性
   *   pitch: SimpleProperty, //动态俯仰角属性
   *   roll: SimpleProperty, //动态横滚角属性
   * } options 
   */
  setFrontView(options) {
    this.viewer.clock.shouldAnimate = true;
    this.listener = (clock) => {
      let position = options.position.getValue(clock.currentTime);
      if(!position) return;
      let heading = options.heading ? options.heading.getValue(clock.currentTime) : 0;
      let pitch = options.pitch ? options.pitch.getValue(clock.currentTime) : 0;
      let roll = options.roll ? options.roll.getValue(clock.currentTime) : 0;
      this.viewer.camera.setView({
        destination: position,
        orientation: {
          heading: Cesium.Math.toRadians(heading),
          pitch: Cesium.Math.toRadians(pitch),
          roll: Cesium.Math.toRadians(roll)
        }
      });
    }
    this.viewer.clock.onTick.addEventListener(this.listener, this);
  }

  // 第三人称视角-自由视角
  setTrackView(entity) {
    this.viewer.trackedEntity = entity;
  }

  /**
   * 第三人称视角-固定视角
   * @param {
   *   position: SampledPositionProperty, //动态位置属性
   *   heading: SimpleProperty, //动态偏航角属性
   *   pitch: Number, //俯仰角度
   *   distance: Number, //目标点距离
   * } options 
   */
  setFixedView(options) {
    this.viewer.clock.shouldAnimate = true;
    this.listener = (clock) => {
      let curPosition = options.position.getValue(clock.currentTime);
      if(!curPosition) return;
      let curHeading = options.heading ? options.heading.getValue(clock.currentTime) : 0;
      let heading = Cesium.Math.toRadians(curHeading);
      // 俯仰角固定-45度
      let pitch = Cesium.Math.toRadians(options.pitch === undefined ? -45 : options.pitch);
      // 视角锁定物体，距离物体22m时，无法再放大
      let offset = new Cesium.HeadingPitchRange(heading, pitch, options.distance || 22);
      this.viewer.camera.lookAt(curPosition, offset);
    }
    this.viewer.clock.onTick.addEventListener(this.listener, this);
  }

  // 重置视角模式
  resetView() {
    if(this.viewer.trackedEntity) this.viewer.trackedEntity = undefined;
    if(this.listener) {
      this.viewer.clock.onTick.removeEventListener(this.listener, this);
      this.listener = null;
    };
    this.viewer.camera.lookAtTransform(Cesium.Matrix4.IDENTITY);
  }
}

Cesium.ViewController = ViewController;